# coding=utf-8
__author__ = 'liubin'

import simplejson as json
from sqlalchemy.orm.collections import InstrumentedList
from common import EXECUTOR

class HandlerMixin(object):
    """
    为了使用sqlalchemy而追加在handker上的mixin
    """
    def get_current_user(self):
        """
        获取当前用户CODE
        """
        return self.get_secure_cookie("user")

    def on_finish(self):
        """
        重新 handler的on_finish
        """
        #print('close')
        try:
            #pass
            #print(self.db_conn)
            # print(self.db_conn.dirty)
            # if self.db_conn.dirty:
            self.db_conn.rollback()
        finally:
            self.db_conn.remove()

    def success(self, data, **pairs):
        """
        重新 handler的success
        """
        res = {'status': 'success', 'data': data}
        if pairs:
            res.update(pairs)
        self.write(res)
        self.finish()

    def prepare(self):
        """
        执行前的准备
        """

        # 获取json_args
        content_type = self.request.headers.get('Content-Type')
        if content_type and content_type.startswith('application/json'):
            self.json_args = json.loads(self.request.body, encoding='utf-8')
        else:
            self.json_args = None

        # 异步必须的参数
        self.executor = EXECUTOR

class JsonpickleMixin(object):
    """
    为了使用Jsonpickle而追加在model上的mixin
    """
    def __getstate__(self):
        '''
        重写model的__getstate__
        :return:
        '''
        state = self.__dict__.copy()
        del state['_sa_instance_state']
        # InstrumentedList的特殊处理(backref相关)
        if type(state) == dict:
            for key, value in state.items():
                if type(value) == InstrumentedList:
                    data = []
                    for item in value:
                        data.append(item.__getstate__())
                    state[key] = data
        return state